<template>
    <div class="verification-code-container">
      <block v-for="(item, index) in codeLength" :key="index">
        <div class="code-box" :class="{ active: currentIndex === index }" @click="setCurrentIndex(index)">
          {{ codeArr[index] || '' }}
          <div class="cursor" v-if="currentIndex === index && isFocus" :animation="cursorAnimation"></div>
        </div>
      </block>
      <input
        ref="inputRef"
        v-model="inputValue"
        :maxlength="codeLength"
        @input="handleInput"
        @focus="setFocus(true)"
        @blur="setFocus(false)"
        style="opacity: 0; position: absolute; top: -9999px"
      />
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        codeLength: 6,
        codeArr: new Array(6).fill(''),
        currentIndex: 0,
        isFocus: false,
        inputValue: '',
        cursorAnimation: null
      };
    },
    mounted() {
      // 初始化光标动画
      this.cursorAnimation = this.$createAnimation({
        duration: 1000,
        timingFunction: 'ease',
        delay: 0
      });
      this.animateCursor();
    },
    methods: {
      setCurrentIndex(index) {
        this.currentIndex = index;
        this.$refs.inputRef.focus();
      },
      handleInput() {
        const inputArr = this.inputValue.split('');
        this.codeArr = new Array(this.codeLength).fill('');
        inputArr.forEach((char, index) => {
          if (index < this.codeLength) {
            this.codeArr[index] = char;
          }
        });
        this.currentIndex = inputArr.length;
      },
      setFocus(isFocus) {
        this.isFocus = isFocus;
      },
      animateCursor() {
        setInterval(() => {
          this.cursorAnimation.opacity(1).step();
          this.cursorAnimation.opacity(0).step();
          this.cursorAnimation.export();
        }, 1000);
      }
    }
  };
  </script>
  
  <style scoped>
  .verification-code-container {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .code-box {
    width: 40px;
    height: 40px;
    border: 1px solid #ccc;
    margin: 0 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
  }
  
  .code-box.active {
    border-color: #007aff;
  }
  
  .cursor {
    width: 2px;
    height: 20px;
    background-color: #007aff;
    animation: blink 1s infinite;
  }
  
  @keyframes blink {
    0% {
      opacity: 1;
    }
    50% {
      opacity: 0;
    }
    100% {
      opacity: 1;
    }
  }
  </style>    